package com.xzmzhp.security;

import com.xzmzhp.constant.ReturnConstant;
import com.xzmzhp.utils.return_tool.ResponseUtil;
import com.xzmzhp.utils.return_tool.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王源（xm）
 * @Date: 2020/12/3 21:03
 * @Description: 登出处理类 返回204
 */
@Component
public class MyLogoutHandler implements LogoutHandler, LogoutSuccessHandler {
    /**
     * token操作工具类
     */
    @Autowired
    private TokenManager tokenManager;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //从header里面获取token
        String token = request.getHeader("token");

        //token不为空，移除token，从redis删除token
        if (token != null) {
            //获取用户信息
            String username = tokenManager.getUserInfoFromToken(response,token);
        }
        ResponseUtil.out(response, new ReturnData(ReturnConstant.NO_CONTENT));
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从header里面获取token
        String token = request.getHeader("token");

        //token不为空，移除token，送redis删除token
        if (token != null) {
            //获取用户信息
            String username = tokenManager.getUserInfoFromToken(response,token);
        }
        ResponseUtil.out(response, new ReturnData(ReturnConstant.NO_CONTENT));
    }
}
